##这个脚本用来调试串口
import crcmod
import serial
import array
import os
import signal
from time import sleep
import time
import re 
from datetime import datetime

flag_stop = False

def get_time_stamp():
    ct = time.time()
    local_time = time.localtime(ct)
    data_head = time.strftime("%Y-%m-%d %H:%M:%S", local_time)
    data_secs = (ct - int(ct)) * 1000
    time_stamp = "%s.%03d" % (data_head, data_secs)
    return time_stamp
    #print(time_stamp)

def onsignal_int(a,b):
    print("sigint!")
    global flag_stop
    flag_stop = True

def confir(str):
    for i in range(0,32):
        str=str.replace(chr(i),'')
    return str

def buildPackage( sendData,packageCount):   
    c8 = crcmod.predefined.mkCrcFun('CRC-8')
    c32 = crcmod.predefined.mkCrcFun('CRC-32')
    
    outData = bytes()
    outData += sendData[0:15]
    outData += packageCount
    outData += c8(outData[8:17]).to_bytes(16 , byteorder = 'little')[0:1] 
    outData += sendData[18:len(sendData)-4]
    outData += c32( outData[8:] ).to_bytes(16 , byteorder = 'little')[0:4] 

    return outData

def buildPrintTaskPackage( sendData, packageCount, curTaskIdBytes ):   
    c8 = crcmod.predefined.mkCrcFun('CRC-8')
    c32 = crcmod.predefined.mkCrcFun('CRC-32')
    
    outData = bytes()
    outData += sendData[0:15] # 帧头
    outData += packageCount # 包会话计数
    outData += c8(outData[8:17]).to_bytes(16 , byteorder = 'little') [0:1]   # 帧头校验
    outData += sendData[18:20] #指令
    outData += curTaskIdBytes  #任务号
    outData += sendData[22:len(sendData)-4]
    outData += c32( outData[8:] ).to_bytes(16 , byteorder = 'little')[0:4] 
    
    return outData

def GetCarveData( sendData, packageCount, curTaskIdBytes, startSteps, needSteps ):   
    c8 = crcmod.predefined.mkCrcFun('CRC-8')
    c32 = crcmod.predefined.mkCrcFun('CRC-32')
    
    outData = bytes()
    outData += sendData[0:15] # 帧头
    outData += packageCount # 包会话计数
    outData += c8(outData[8:17]).to_bytes(16 , byteorder = 'little')[0:1]    # 帧头校验
    outData += sendData[18:20] #指令
    outData += curTaskIdBytes  #任务号
    outData += B'\xd0'  #数据类型
    outData += startSteps  #起始步长
    outData += needSteps  #请求包数量
    outData += c32( outData[8:] ).to_bytes(16 , byteorder = 'little')[0:4]
    
    return outData

def main():
    signal.signal(signal.SIGINT, onsignal_int)
    signal.signal(signal.SIGTERM, onsignal_int)

    ser = serial.Serial('COM7', 57600, bytesize=8, parity='E', stopbits=2, timeout=1)
    print("serial.isOpen() =",ser.isOpen())

    cmd_back = B""
    printStep = 0

    curTaskId = 0
    curTaskIdBytes = bytes()
    lastRevPrintData = datetime.now()

    while True:
        sleep(0.1)

        if flag_stop:                # read data until Ctrl+c
            #ser.write(stop)            # send cmd stop before exit
            print("reset cmd has been sent!")
            break

        text = ser.read(1)          # read one, with timout
        if len(text) > 0:                    # check if not timeout
            sleep(0.01)
            n = ser.inWaiting()     # look if there is more to read
            if n:
                text = text + ser.read(n) #get it
            cmd_back = cmd_back + text
            text = B""
            
            #print("收到数据：", cmd_back.hex(" "))

            cmdList = cmd_back.split(B"\xeb\xeb\xeb\xeb\xeb\xeb")
            for cmdItem in cmdList:
                #print(cmdItem)
                #B"\x00\x00\xf1\x01\x10\x01\x00\x13\x00\x02\x00A\x00\x01R\t\x00\x00\x01\x01\x00T\x97\xf8y"
                if(cmdItem[2:3] == B"\xf1"  and cmdItem[12:14] == B"\x00\x01"):#收到打印任务
                    packageCount = cmdItem[9:11]  #会话计数
                    
                    print(get_time_stamp(), "==> 接收到打印任务.", packageCount.hex(" "))
                    curTaskId += 1
                    curTaskIdBytes = (curTaskId).to_bytes(16 , byteorder = 'little')[0:2] 
                    printStep = 1

                    sendData = B"\xeb\xeb\xeb\xeb\xeb\xeb\x00\x00\xf1\x01\x00\x01\x10\x0f\x00\x02\x00\x2f\x00\x11\x01\x00\x01\x82\x1a\x1b\x55"    
                    outData = buildPrintTaskPackage( sendData, packageCount, curTaskIdBytes )
                    print("<== ", outData.hex(" "))
                    s = ser.write(outData)
                    ser.flush()
                    
                    sleep(0.05)
                    #获取各打印头打印数据
                    sendData = B"\xeb\xeb\xeb\xeb\xeb\xeb\x00\x00\xd0\x01\x00\x01\x10\x15\x00\x01\x00\x9f\x01\x00\x01\x00\xa0\x00\x00\x00\x00\xfe\x07\x01\x4d\xe9\xcb"
                    outData = buildPrintTaskPackage( sendData, packageCount, curTaskIdBytes )
                    print("<== ", get_time_stamp(), outData.hex(" "))
                    s = ser.write(outData)
                    ser.flush()
                    
                    sendData = B"\xeb\xeb\xeb\xeb\xeb\xeb\x00\x00\xd0\x01\x00\x01\x10\x15\x00\x01\x00\x9f\x01\x00\x01\x00\xa1\x00\x00\x00\x00\xfe\x07\xb5\x46\x9e\x6d"
                    outData = buildPrintTaskPackage( sendData, packageCount, curTaskIdBytes )
                    print("<== ", get_time_stamp(), outData.hex(" "))
                    s = ser.write(outData)
                    ser.flush()

                    sendData = B"\xeb\xeb\xeb\xeb\xeb\xeb\x00\x00\xd0\x01\x00\x01\x10\x15\x00\x01\x00\x9f\x01\x00\x01\x00\xa2\x00\x00\x00\x00\xfe\x07\x28\x5c\x76\x5c"
                    outData = buildPrintTaskPackage( sendData, packageCount, curTaskIdBytes )
                    print("<== ", get_time_stamp(), outData.hex(" "))
                    s = ser.write(outData)
                    ser.flush()
                    
                    print("--- 准备接收打印数据 ---")
                    #continue

                # 收到打印数据
                elif(cmdItem[2:3] == B"\xd0"  and cmdItem[12:14] == B"\x10\x00"):
                    if printStep == 1 :
                        printStep = 2
                    lastRevPrintData = datetime.now()
                    print("==> 接收到打印数据：", packageCount[0:20].hex(" "))
                    #continue

                # 收到模切数据
                elif(cmdItem[2:3] == B"\xd1"  and cmdItem[12:14] == B"\x10\x00"):
                    print("==> 接收到模切数据.", packageCount[0:20].hex(" "))
                    #continue
                    
                else:
                    print("==> 未处理数据:", cmdItem[6:7].hex(" "), cmdItem[16:18].hex(" "), cmdItem[0:20].hex(" "))

                print("-------------")
                cmd_back = B""

        if (printStep == 2) and ((datetime.now() - lastRevPrintData).total_seconds() > 5.0):  # 超过5S钟没有收到打印数据
            printStep = 3
            #获取模切数据
            print("-- 请求模切数据:", packageCount)
            sendData = B"\xeb\xeb\xeb\xeb\xeb\xeb\x00\x00\xd1\x01\x00\x01\x10\x15\x00\x10\x00\x2f\x01\x00\x01\x00\xd1\x00\x04\x00\x00\x00\x04\x00\x00\x00\x04"    
            startSteps = (0).to_bytes(16 , byteorder = 'little')[0:4] 
            needSteps = (1024).to_bytes(16 , byteorder = 'little')[0:2] 
            outData = GetCarveData( sendData, packageCount, curTaskIdBytes, startSteps, needSteps )
            print("<== ", outData.hex(" "))
            s = ser.write(outData)

    ser.close()

    
if __name__ == "__main__":
    main()
